package soporte;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @project DLC Final / UTN FRC 2013
 * @date Febrero de 2013
 *
 * @author Gonzalo Arribere
 * @author Gustavo Morales
 * @author Pablo Moreno
 *
 * Esta clase se utiliza para eliminar de un termino todos aquellos caracteres o
 * simbolos raros que no pertenecen al alfabeto español.
 */
public class WordCleaner {

    private Pattern[] mPatternClean;
    private Pattern[] mPatternFix;
    private static final String[] REPLACES = {
        "a", "e", "i", "o", "u", "c", "ñ", ""
    };
    private static final String[] REPLACES_FIX = {
        "á", "é", "Á", "ñ"
    };
    private static WordCleaner INSTANCE = new WordCleaner();

    private WordCleaner() {
        compilePatterns();
    }

    private void compilePatterns() {
        mPatternClean = new Pattern[REPLACES.length];
        mPatternClean[0] = Pattern.compile("[âãáàäÂÃÁÀÄ]");
        mPatternClean[1] = Pattern.compile("[éèêëÉÈÊË]");
        mPatternClean[2] = Pattern.compile("[íìîïÍÌÎÏ]");
        mPatternClean[3] = Pattern.compile("[óòôõöÓÒÔÕÖ]");
        mPatternClean[4] = Pattern.compile("[úùûüÚÙÛÜ]");
        mPatternClean[5] = Pattern.compile("[çÇ]");
        mPatternClean[6] = Pattern.compile("[ñÑ]");
        mPatternClean[7] = Pattern.compile("[^\\wñ]");

        mPatternFix = new Pattern[REPLACES_FIX.length];
        mPatternFix[0] = Pattern.compile("Æ");
        mPatternFix[1] = Pattern.compile("Ø");
        mPatternFix[2] = Pattern.compile("`");
        mPatternFix[3] = Pattern.compile("æ");
    }

    /**
     * Corrige una palabra mal parseada por el PDF parser. Mantiene
     * mayúsculas/minúsculas ejemplo: Real: Cadáver Parseda: CadÆver Corregida:
     * Cadáver
     *
     * @param pWord
     * @return
     */
    public static String sanatize(String pWord) {
        return INSTANCE.fixString(pWord).trim();
    }

    /**
     * Limpia una palabra a solo letras: a-z ó 0-9, los acentos serán removidos
     * y si hay otros simbolos los eliminará
     *
     * @param pWord
     * @return
     */
    public static String clean(String pWord) {
        return INSTANCE.cleanString(pWord);
    }

    private String cleanString(String pWord) {
        String result = pWord;
        for (int i = 0; i < mPatternClean.length; i++) {
            Matcher matcher = mPatternClean[i].matcher(result);
            result = matcher.replaceAll(REPLACES[i]);
        }
        return result.toLowerCase();
    }

    private String fixString(String pWord) {
        String result = pWord;
        for (int i = 0; i < mPatternFix.length; i++) {
            Matcher matcher = mPatternFix[i].matcher(result);
            result = matcher.replaceAll(REPLACES_FIX[i]);
        }
        return result;
    }
}